//
//  userSubmitQustionVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/8/29.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "UserSubmitQustionVC.h"
#import "LineQuestionHeadView.h"
#import "UserSubmitQuestionCell.h"
#import "AskQuestionVC.h"

@interface UserSubmitQustionVC ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong)UITableView * tableView;

@property (nonatomic, strong)NSMutableArray * dataSource;

@property (nonatomic, strong)LineQuestionHeadView * lineQuestionHeaderView;

@property (nonatomic, strong)UIButton *submitBtn;

@property (nonatomic, strong) UserSubmitQuestionCell *currentCell;
@property (nonatomic, strong) Question *cquestion;

@property (nonatomic)CGFloat toBottonSpace;

@end

@implementation UserSubmitQustionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setup];
    
    
    [ActivityIndicatorView showHUDAddedTo:self.view backgroundColor:[UIColor whiteColor]];
    [self loadData];
    
    @weakify(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        [self loadData];
    }];
    [self.tableView setThemeStyle:ThemeStyleBlack];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAudioState:) name:kPlayManagerState object:nil];
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    [[PlayerManager shareManeger] stop];
}


- (LineQuestionHeadView *)lineQuestionHeaderView {
    
    if (!_lineQuestionHeaderView) {
        _lineQuestionHeaderView = [[LineQuestionHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 120)];
        _lineQuestionHeaderView.backgroundColor = [UIColor whiteColor];
    }
    
   return  _lineQuestionHeaderView;
}

- (void)loadData {
    
    @weakify(self);
    [NetAPIManager getAllQuestionsWithLineID:self.lineModel.lineid pageno:@0 pigesize:@1000 Block:^(NSDictionary *guiderInfo, NSArray<Question *> *questionArray, NSError *error) {
        @strongify(self);
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        [self.tableView.mj_header endRefreshing];
        self.dataSource = [NSMutableArray arrayWithArray:questionArray];
        
        self.lineQuestionHeaderView.lineName = guiderInfo[@"lineName"];
        self.lineQuestionHeaderView.guiderName = guiderInfo[@"guideName"];
        self.lineQuestionHeaderView.num = questionArray.count;
        self.lineQuestionHeaderView.vip = [guiderInfo[@"guideVip"] integerValue];
        self.lineQuestionHeaderView.headerImageName = guiderInfo[@"guideFace"];
        [self.tableView reloadData];
        
        if ([guiderInfo[@"canask"] boolValue]) {
            [self.view addSubview:self.submitBtn];
        } else {
             
            [self.submitBtn removeFromSuperview];
            CGRect tbRect = self.tableView.frame;
            tbRect.size.height = SCREEN_HEIGHT - kNavigationBarHeight;
            self.tableView.frame = tbRect;
        }
    }];
}

- (void)setup {
    
    if (ISiPhoneX) {
        self.toBottonSpace = 34;
    }
    
    self.barBGAlpha = 1.0f;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, SCREEN_WIDTH , SCREEN_HEIGHT - kNavigationBarHeight - 49 - self.toBottonSpace) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.estimatedRowHeight = 44;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.tableHeaderView = self.lineQuestionHeaderView;
    _tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"UserSubmitQuestionCell" bundle:nil] forCellReuseIdentifier:@"UserSubmitQuestionCell"];
    
    [self.tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"headerView"];
    self.title = MYLocalizedString(@"SITEPLAY_USER_QUESTION", nil);
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (UIButton *)submitBtn {
    
    if (!_submitBtn) {
        
        _submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitBtn.frame = CGRectMake(0, SCREEN_HEIGHT - 49 - self.toBottonSpace, SCREEN_WIDTH, 49);
        [_submitBtn setBackgroundColor:kThemeColor];
        [_submitBtn setTitle:MYLocalizedString(@"SITEPLAY_SUBMIT_QUESTION", nil) forState:UIControlStateNormal];
        [_submitBtn addTarget:self action:@selector(writeQuestion) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _submitBtn;
}

- (void)writeQuestion {
    
    AskQuestionVC *questionVC = [AskQuestionVC new];
    questionVC.lineModel = self.lineModel;
    questionVC.delegate = self;
    [self.navigationController pushViewController:questionVC animated:YES];
}
#pragma mark - AskQuestionVCDelegate
- (void)AskQuestuibDone {
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)changeAudioState:(NSNotification *)notif {
    
    NSInteger state = [notif.userInfo[kPlayManagerState] integerValue];
    NSString  *url = notif.userInfo[kCurrentPlayURL];
    
    if (![url isEqualToString:self.cquestion.answer]) {
        return;
    }
    
    switch (state) {
        case AVPlayerPlayStatePause:
        case AVPlayerPlayStateEnd:
        {
            [self.currentCell stopPlay];
            self.cquestion = nil;
            self.currentCell = nil;
            
        }
            break;
    }
}


#pragma mark  --UITableViewDelegate,UITableViewDataSource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UserSubmitQuestionCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UserSubmitQuestionCell"];
    cell.delegate = self;
    cell.superVC = self;
    Question *qusetion = self.dataSource[indexPath.row];
    
    cell.question = qusetion;
    
    if ([self.cquestion.qid isEqualToString:qusetion.qid]) {
        [cell startPlay];
    } else {
        [cell stopPlay];
    }
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    headerView.backgroundColor = [UIColor clearColor];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 8;
}

#pragma mark - UserSubmitQuestionCellDelegate

- (void)answerAudioTapped:(UserSubmitQuestionCell *)cell question:(Question *)question {
    
    if ([question.qid isEqualToString:self.cquestion.qid]) {
        [[PlayerManager shareManeger] pause];
        return;
    }
    
    if ([IGAvPlayerManager shareManeger].isPlay) {
        [[IGAvPlayerManager shareManeger] pause];
    }
    if ([[PlayerManager shareManeger].currentURL isEqualToString:question.answer]) {
        [[PlayerManager shareManeger] play];
    } else {
        
        if ([[PlayerManager shareManeger].currentURL isEqualToString:self.cquestion.answer]) {
            [self.currentCell stopPlay];
        }
        
        [[PlayerManager shareManeger] playAnswerVideoWith:question.answer];
    }
    
    [NetAPIManager clickCountWithID:question.qid type:@(3).stringValue];
    self.currentCell = cell;
    self.cquestion = question;
    [cell startPlay];
}

@end
